{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "def callback (datas):\n",
    "    print(datas)\n",
    "xtdata.subscribe_quote(stock_code='600519.SH', period='1m', callback=callback)\n",
    "xtdata.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "xtdata.download_sector_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "\n",
    "def update_progress(progress):\n",
    "    '''进度条'''\n",
    "    bar_length = 40  # 进度条长度\n",
    "    block = int(round(bar_length * progress))\n",
    "    text = f\"\\r[{'#' * block + '-' * (bar_length - block)}] {progress * 100:.2f}%\"\n",
    "    if progress < 1:\n",
    "        print(text, end='', flush=True)\n",
    "    else:\n",
    "        print(text, flush=True)\n",
    "\n",
    "\n",
    "stock_list = xtdata.get_stock_list_in_sector('沪深300')\n",
    "print(stock_list)\n",
    "# 实时订阅\n",
    "def subscribe():\n",
    "    print('开始订阅')\n",
    "\n",
    "    for index, stock in enumerate(stock_list):\n",
    "\n",
    "        def on_data(res, stock=stock):\n",
    "            print(res, stock)\n",
    "\n",
    "        xtdata.subscribe_quote(stock_code=stock, period='1d', callback=on_data)\n",
    "        update_progress((index+1)/len(stock_list))\n",
    "    \n",
    "    xtdata.run()\n",
    "\n",
    "subscribe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "stock_list = xtdata.get_stock_list_in_sector('沪深300')\n",
    "def callback (datas):\n",
    "    print(datas)\n",
    "xtdata.subscribe_whole_quote(code_list=stock_list, callback=callback)\n",
    "xtdata.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "import time\n",
    "def callback (datas):\n",
    "    print(datas)\n",
    "seq = xtdata.subscribe_quote(stock_code='600519.SH', period='1d', callback=callback)\n",
    "print(seq)\n",
    "time.sleep(10)\n",
    "res = xtdata.unsubscribe_quote(seq)\n",
    "print(res)\n",
    "xtdata.run()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "# stock_list = xtdata.get_stock_list_in_sector('沪深300')\n",
    "res = xtdata.get_full_tick(code_list=['600519.SH'])\n",
    "res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "res = xtdata.get_market_data_ex(stock_list=['600519.SH'], period='1d', start_time='20240101')\n",
    "res['600519.SH']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xtquant import xtdata\n",
    "import logging\n",
    "from datetime import datetime\n",
    "xtdata.enable_hello = False\n",
    "# =====设置参数=====\n",
    "\n",
    "period = 'tick' # 周期，可选值 {'tick', '1m', '5m', '1d'}等\n",
    "stock_list = xtdata.get_stock_list_in_sector('沪深300')\n",
    "\n",
    "# ====log配置=====\n",
    "\n",
    "logging.basicConfig(\n",
    "    level=logging.INFO,\n",
    "    format='[%(asctime)s] %(message)s',\n",
    "    datefmt='%Y-%m-%d %H:%M:%S'\n",
    ")\n",
    "\n",
    "# =====主程序=====\n",
    "\n",
    "def update_progress(progress):\n",
    "    '''进度条'''\n",
    "    bar_length = 40  # 进度条长度\n",
    "    block = int(round(bar_length * progress))\n",
    "    text = f\"\\r[{'#' * block + '-' * (bar_length - block)}] {progress * 100:.2f}%\"\n",
    "    if progress < 1:\n",
    "        print(text, end='', flush=True)\n",
    "    else:\n",
    "        print(text, flush=True)\n",
    "\n",
    "def calculate_seconds_difference(specified_time):\n",
    "    # 将输入字符串转换为datetime对象\n",
    "    \n",
    "    # 获取当前系统时间\n",
    "    current_time = datetime.now().timestamp()\n",
    "    \n",
    "    # 计算时间差\n",
    "    time_difference =  current_time - (specified_time / 1000)\n",
    "    \n",
    "    return time_difference\n",
    "    \n",
    "\n",
    "# 实时订阅\n",
    "def subscribe(stock_list):\n",
    "    logging.info('开始订阅')\n",
    "\n",
    "    ready = False\n",
    "\n",
    "    for index, stock in enumerate(stock_list, start=1):\n",
    "\n",
    "        def on_data(res, stock=stock):\n",
    "            if not ready:\n",
    "                return\n",
    "            dff = calculate_seconds_difference(res[stock][0]['time'])\n",
    "            if period != 'tick':\n",
    "                close_value = res[stock][0]['close']\n",
    "            else:\n",
    "                close_value = res[stock][0]['lastPrice']\n",
    "            # if dff > 3:\n",
    "            logging.info(f'时间戳：{res[stock][0][\"time\"]}, 股票代码：{stock}, 当前价格：{close_value}, 延迟：{dff}')\n",
    "\n",
    "        xtdata.subscribe_quote(stock_code=stock, period=period, count=1, callback=on_data)\n",
    "        update_progress(index/len(stock_list))\n",
    "    ready = True\n",
    "        \n",
    "\n",
    "def main():\n",
    "    subscribe(stock_list)\n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "    xtdata.run()\n",
    "    \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
